package com.qiyee.dalligent;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFSimpleShape;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class BarcodeGenerator2 {

    private static final Integer CODE_WIDTH = 100;                 // 基础属性：二维码宽度，单位像素
    private static final Integer CODE_HEIGHT = 30;                // 基础属性：二维码高度，单位像素
    private static final Integer FRONT_COLOR = 0x000000;           // 基础属性：二维码前景色，0x000000 表示黑色
    private static final Integer BACKGROUND_COLOR = 0xFFFFFF;      // 基础属性：二维码背景色，0xFFFFFF 表示白色

    public static void main(String[] args) throws Exception {

        //设置生成条形码的内容（注：条形码信息一定要按照格式，如随便一个商品上的条形码都行，但必须是EAN_13格式）
        String qrMessage = "8894796215296711"+new Random().nextInt(100);

        // EncodeHintType：指定和控制码生成器的一些参数的类
        Map<EncodeHintType, Object> typeObjectHashMap = new HashMap<EncodeHintType, Object>();
        // 设置编码
        typeObjectHashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 设置容错等级
        typeObjectHashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 设置边距，默认为5
        typeObjectHashMap.put(EncodeHintType.MARGIN, 3);

        // MultiFormatWriter:用于写入条形码或二维码
        Code128Writer multiFormatWriter = new Code128Writer();
        BitMatrix bitMatrix = multiFormatWriter
            .encode(qrMessage, BarcodeFormat.CODE_128, CODE_WIDTH, CODE_HEIGHT, typeObjectHashMap);

        // java.awt.image.BufferedImage：把条形码信息转换为图像信息
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);;
       /* for (int x = 0; x < CODE_WIDTH; x++) {
            for (int y = 0; y < CODE_HEIGHT; y++) {
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR);
            }
        }*/

        // javax.imageio.ImageIO 将图片信息写出到文件

        String path = qrMessage + ".png";

        //ImageIO.write(bufferedImage, "png", new FileOutputStream(path));
        exportToExcel(qrMessage,bufferedImageToByteArray(bufferedImage),2);
    }

    public static byte[] bufferedImageToByteArray(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        return baos.toByteArray();
    }
    public static void exportToExcel(String fileName,byte[] bytes,int i) throws Exception{
        String name = fileName + ".xlsx";
        Workbook workbook = new XSSFWorkbook(); // 创建工作簿
        Sheet sheet = workbook.createSheet("Barcodes"); // 创建工作表
        // 创建标题行的样式

        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);
        Row row = sheet.createRow(0); // 创建第一行
        Cell cell = row.createCell(0); // 创建单元格
        Cell cell2 = row.createCell(2); // 创建单元格
        cell.setCellValue("Barcode Image"); // 设置单元格内容
        cell2.setCellValue("Barcode Image2"); // 设置单元格内容
        // 设置单元格样式
        CellStyle style = workbook.createCellStyle();
        // 设置字体
        Font headerFont = workbook.createFont();
        headerFont.setBold(true); // 设置为加粗
        headerFont.setFontHeightInPoints((short)16);
        style.setFont(headerFont);
        sheet.setDefaultColumnWidth(30);
        sheet.setDefaultRowHeightInPoints(24);
        style.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        style.setWrapText(true);
        style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); // 背景颜色
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 填充模式
        cell.setCellStyle(style);
        cell.setAsActiveCell();
        cell2.setCellStyle(style);
        cell2.setAsActiveCell();
        FileOutputStream outputStream = new FileOutputStream(name);
        for (int i1 = 0; i1 < i; i1++) {
            Drawing drawing = sheet.createDrawingPatriarch();
            // int col1 设置图片开始的列索引, int row1, int col2, int row2
            ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, i1*2 , 1, i1*2  + 1, 2);
            drawing.createPicture(anchor,
                workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG));

            /*// 插入条码图片
            int pictureIndex =
                workbook.addPicture(Files.readAllBytes(Paths.get(barcodeFilePath)), Workbook.PICTURE_TYPE_PNG);
            CreationHelper helper = workbook.getCreationHelper(); // 创建帮助器
            Drawing drawing = sheet.createDrawingPatriarch();
            // XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 0, 0, 0, 1);
            ClientAnchor anchor = helper.createClientAnchor();
            anchor.setCol1(0+i1);// 设置图片开始的列索引
            anchor.setRow1(1);// 设置图片开始的行索引
            anchor.setCol2(1+i1);
            anchor.setRow2(2+i1);
            anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
            drawing.createPicture(anchor, pictureIndex).resize(); // 设置图片大小
*/
        }

        workbook.write(outputStream);
        // 保存Excel文件

        System.out.printf("filName:" + name);
        workbook.close(); // 关闭工作簿

    }
}